import { native } from "cc";
import NativeClient, { NativeClientIns } from "./NativeClient";

/** 原生端行为模拟 */
class iOSClient extends NativeClientIns {
	private static $planet_response_cache_poof$: Map<string, [abd.$planet_NudityPromise_poof$<any>, any]> = new Map();
	private static $planet_used_token_poof$: string[] = [];

	public callStaticMethod(api: string, data: any, ccdata?: any){
		return iOSClient.request(api, data, ccdata);
	}

	private static request($planet_api_poof$: string, $planet_data_poof$: any, ccdata?: any){
		let token = abd.$planet_string_poof$.$planet_randomToken_poof$(5, 36, t=>!iOSClient.$planet_used_token_poof$.includes(t));
		let np = new abd.$planet_NudityPromise_poof$();

		iOSClient.$planet_used_token_poof$.push(token);
		iOSClient.$planet_response_cache_poof$.set(token, [np, ccdata]);

		let $planet_request_poof$ = {
			$planet_cc_token_poof$: token,
			$planet_data_poof$
		};
		native.reflection.callStaticMethod('$planet_MessageManager_poof$', '$planet_callNative_poof$WithName:data:', $planet_api_poof$, JSON.stringify($planet_request_poof$));
		return {$planet_api_poof$, $planet_request_poof$, $planet_response_poof$: np.$planet_promise_poof$};
	}

	private static response(api: string, json_string: string){
		let response = JSON.parse(json_string);
		let token = response.$planet_cc_token_poof$;
		let [np, ccdata] = iOSClient.$planet_response_cache_poof$.get(token);
		iOSClient.$planet_response_cache_poof$.delete(token);
		abd.$planet_array_poof$.$planet_remove_poof$(iOSClient.$planet_used_token_poof$, token);

		response.$planet_cc_token_poof$ = ccdata ?? token;
		np.$planet_resolve_poof$(response);
	}
}

//NativeClient.initClient(new iOSClient());
//Reflect.set(globalThis ?? window, "iOSClient", iOSClient);